import requests
import hmac
import hashlib
import time
from decimal import Decimal


def place_bnb_limit_order(api_key, api_secret, price=969.38, quantity=0.01, testnet=True):
    """快速下限价单购买BNB"""

    # 设置参数
    symbol = "BNBUSDT"
    side = "BUY"
    order_type = "LIMIT"
    time_in_force = "GTC"  # 成交为止

    # 选择API端点
    base_url = "https://testnet.binance.vision" if testnet else "https://api.binance.com"
    endpoint = "/api/v3/order"

    # 获取服务器时间
    try:
        time_response = requests.get(f"{base_url}/api/v3/time")
        timestamp = time_response.json()['serverTime']
    except:
        timestamp = int(time.time() * 1000)

    # 构建查询参数
    params = (
        f"symbol={symbol}&"
        f"side={side}&"
        f"type={order_type}&"
        f"timeInForce={time_in_force}&"
        f"quantity={quantity}&"
        f"price={price}&"
        f"timestamp={timestamp}&"
        f"recvWindow=5000"
    )

    # 创建签名
    signature = hmac.new(
        api_secret.encode('utf-8'),
        params.encode('utf-8'),
        hashlib.sha256
    ).hexdigest()

    # 构建完整URL
    url = f"{base_url}{endpoint}?{params}&signature={signature}"
    headers = {"X-MBX-APIKEY": api_key}

    # 发送请求
    try:
        response = requests.post(url, headers=headers, timeout=10)
        result = response.json()

        if "orderId" in result:
            print("限价委托单提交成功!")
            print(f"订单ID: {result['orderId']}")
            print(f"数量: {result['origQty']} BNB")
            print(f"价格: {result['price']} USDT")
            print(f"状态: {result['status']}")
            return result
        else:
            print("委托单提交失败!")
            print(f"错误: {result}")
            return result
    except Exception as e:
        print(f"请求失败: {e}")
        return {"error": str(e)}


# 使用示例
if __name__ == "__main__":
    # API_KEY = "your_api_key_here"
    # API_SECRET = "your_api_secret_here"
    API_KEY = "oMlYVBgANplqH7XilK0rzJ47r7p1R3MWoywVNBYOGvj5UHYXebQnxZjX9kLpdd5V"
    API_SECRET = "8587vRjV45QsPPXhlrn3vcBdUwQJFA6HIBqfaVbJO7UqhhqTcVrQCR4GEO6w4OtN"
    # 以969.38价格买入0.01 BNB
    result = place_bnb_limit_order(API_KEY, API_SECRET, price=969.38, quantity=0.01, testnet=False)